package com.xuecheng.content.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.content.entity.CoursePubMsg;
import com.xuecheng.content.service.CoursePubMsgService;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 扫描发送失败的消息
 */
@Slf4j
@Component
public class CoursePublishTask {

    @Autowired
    private CoursePubMsgService coursePubMsgService;

    @Autowired
    private CoursePubService coursePubService;

    /**
     * 查询课程发布消息状态为未发布的数据，重新投递消息到MQ
     * 5s 查询一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void testTask() {
        log.info("component course_pub_msg...");
        LambdaQueryWrapper<CoursePubMsg> pubMsgQueryWrapper = new LambdaQueryWrapper<>();
        pubMsgQueryWrapper.eq(CoursePubMsg::getPubStatus, CoursePubMsg.UNSENT);
        List<CoursePubMsg> coursePubMsgList = coursePubMsgService.getBaseMapper().selectList(pubMsgQueryWrapper);
        if (!CollectionUtils.isEmpty(coursePubMsgList)) {
            coursePubMsgList.forEach(coursePubMsg -> {
                log.warn("confirmCallback可能出错，导致消息重新投递，coursePubId => {}", coursePubMsg.getPubId());
                // 重新投递消息
                coursePubService.publish(coursePubMsg.getCourseId(), coursePubMsg.getCompanyId(), true);
            });
        }
    }
}
